import Taro from '@tarojs/taro';
import React, { useState, useEffect } from 'react';
import { View, Text, Image, ScrollView, ImageViewer } from '@tarojs/components';
// Taro在小程序平台使用View替代TouchableOpacity
const TouchableOpacity = View;
import { MaterialIcons } from 'taro-icons';
import './index.scss';

// 评价类型定义
interface Evaluation {
  id: number;
  studentName: string;
  studentAvatar: string;
  rating: number;
  content: string;
  images: string[];
  createTime: string;
  courseType: string;
  // 点赞相关字段
  liked: boolean;
  likeCount: number;
  // 不赞同相关字段
  agreed: boolean; // 这里使用agreed表示不赞同，与需求保持一致
  agreedCount: number;
}

// 评分统计类型定义
interface RatingStats {
  totalCount: number;
  averageRating: number;
  ratingDistribution: {
    5: number;
    4: number;
    3: number;
    2: number;
    1: number;
  };
}

const CoachEvaluationPage: React.FC = () => {
  const [evaluations, setEvaluations] = useState<Evaluation[]>([]);
  const [ratingStats, setRatingStats] = useState<RatingStats>({
    totalCount: 0,
    averageRating: 0,
    ratingDistribution: {
      5: 0,
      4: 0,
      3: 0,
      2: 0,
      1: 0
    }
  });
  const [isLoading, setIsLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [activeFilter, setActiveFilter] = useState('all'); // all, course, rating
  const [courseFilter, setCourseFilter] = useState('');
  const [ratingFilter, setRatingFilter] = useState(0);
  // 图片预览相关状态
  const [previewImages, setPreviewImages] = useState<string[]>([]);
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const [showImagePreview, setShowImagePreview] = useState(false);

  useEffect(() => {
    // 设置页面标题
    Taro.setNavigationBarTitle({ title: '教练评价' });
    // 加载评价数据
    loadEvaluationData();
  }, []);

  // 加载评价数据
  const loadEvaluationData = async (refresh = false) => {
    try {
      if (refresh) {
        setRefreshing(true);
      } else {
        setIsLoading(true);
      }
      
      // 从API获取评价数据
      const res = await Taro.request({
        url: 'https://api.example.com/coach/evaluations', // 实际API地址
        method: 'GET',
        header: {
          'content-type': 'application/json'
        }
      });
      
      if (res.statusCode === 200 && res.data?.data) {
        const evaluationsData = res.data.data;
        setEvaluations(evaluationsData);
        
        // 计算评分统计
        calculateRatingStats(evaluationsData);
      } else {
        throw new Error('获取评价数据失败');
      }
    } catch (error) {
      console.error('加载评价数据失败:', error);
      Taro.showToast({
        title: '数据加载失败，请重试',
        icon: 'none'
      });
    } finally {
      setIsLoading(false);
      setRefreshing(false);
    }
  };

  const calculateRatingStats = (data: Evaluation[]) => {
    const totalCount = data.length;
    const distribution = {
      5: 0,
      4: 0,
      3: 0,
      2: 0,
      1: 0
    };
    
    let totalScore = 0;
    data.forEach(item => {
      distribution[item.rating]++;
      totalScore += item.rating;
    });
    
    const averageRating = totalCount > 0 ? (totalScore / totalCount).toFixed(1) : '0.0';
    
    setRatingStats({
      totalCount,
      averageRating: parseFloat(averageRating),
      ratingDistribution: distribution
    });
  };

  // 处理点赞/取消点赞
  const handleLike = async (evaluationId: number) => {
    try {
      const evaluation = evaluations.find(item => item.id === evaluationId);
      if (!evaluation) return;
      
      // 调用API进行点赞/取消点赞操作
      const res = await Taro.request({
        url: `https://api.example.com/coach/evaluations/${evaluationId}/like`,
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        data: {
          liked: !evaluation.liked
        }
      });
      
      if (res.statusCode === 200) {
        // 更新本地状态，确保点赞和不赞同互斥
        setEvaluations(prev => prev.map(item => 
          item.id === evaluationId 
            ? { 
                ...item, 
                liked: !item.liked,
                likeCount: item.liked ? item.likeCount - 1 : item.likeCount + 1,
                // 如果点赞，则取消不赞同状态
                agreed: !item.liked ? false : item.agreed,
                agreedCount: !item.liked && item.agreed ? item.agreedCount - 1 : item.agreedCount
              }
            : item
        ));
      }
    } catch (error) {
      console.error('点赞操作失败:', error);
      Taro.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      });
    }
  };

  // 处理不赞同/取消不赞同
  const handleDisagree = async (evaluationId: number) => {
    try {
      const evaluation = evaluations.find(item => item.id === evaluationId);
      if (!evaluation) return;
      
      // 调用API进行不赞同/取消不赞同操作
      const res = await Taro.request({
        url: `https://api.example.com/coach/evaluations/${evaluationId}/agree`,
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        data: {
          agreed: !evaluation.agreed
        }
      });
      
      if (res.statusCode === 200) {
        // 更新本地状态，确保点赞和不赞同互斥
        setEvaluations(prev => prev.map(item => 
          item.id === evaluationId 
            ? { 
                ...item, 
                agreed: !item.agreed,
                agreedCount: item.agreed ? item.agreedCount - 1 : item.agreedCount + 1,
                // 如果不赞同，则取消点赞状态
                liked: !item.agreed && item.liked ? false : item.liked,
                likeCount: !item.agreed && item.liked ? item.likeCount - 1 : item.likeCount
              }
            : item
        ));
      }
    } catch (error) {
      console.error('不赞同操作失败:', error);
      Taro.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      });
    }
  };

  // 处理图片预览
  const handleImagePress = (images: string[], index: number) => {
    setPreviewImages(images);
    setCurrentImageIndex(index);
    setShowImagePreview(true);
  };

  // 关闭图片预览
  const closeImagePreview = () => {
    setShowImagePreview(false);
  };

  // 下拉刷新
  const onRefresh = () => {
    loadEvaluationData(true);
  };

  const renderStars = (rating: number) => {
    return Array(5).fill(0).map((_, index) => (
      <MaterialIcons 
        key={index}
        name={index < rating ? 'star' : 'star-border'}
        size={16}
        color={index < rating ? '#faad14' : '#d9d9d9'}
      />
    ));
  };

  const filteredEvaluations = evaluations.filter(evaluation => {
    if (activeFilter === 'course' && courseFilter && evaluation.courseType !== courseFilter) {
      return false;
    }
    if (activeFilter === 'rating' && ratingFilter > 0 && evaluation.rating !== ratingFilter) {
      return false;
    }
    return true;
  });

  return (
    <View className="coach-evaluation-page">
      {/* 评分统计卡片 */}
      <View className="rating-stats-card">
        <View className="rating-score">
          <Text className="score-number">{ratingStats.averageRating}</Text>
          <View className="stars-container">
            {renderStars(Math.round(ratingStats.averageRating))}
          </View>
          <Text className="evaluation-count">{ratingStats.totalCount}条评价</Text>
        </View>
        <View className="rating-distribution">
          {[5, 4, 3, 2, 1].map(star => {
            const count = ratingStats.ratingDistribution[star];
            const percentage = ratingStats.totalCount > 0 
              ? Math.round((count / ratingStats.totalCount) * 100) 
              : 0;
            
            return (
              <View key={star} className="rating-item">
                <View className="rating-header">
                  <Text className="star-number">{star}星</Text>
                  <Text className="rating-percentage">{percentage}%</Text>
                </View>
                <View className="rating-bar-container">
                  <View 
                    className="rating-bar-fill" 
                    style={{ width: `${percentage}%` }}
                  />
                </View>
              </View>
            );
          })}
        </View>
      </View>

      {/* 筛选栏 */}
      <View className="filter-bar">
        <ScrollView scrollX showsHorizontalScrollIndicator={false}>
          <View 
            className={`filter-item ${activeFilter === 'all' ? 'active' : ''}`}
            onClick={() => {
              setActiveFilter('all');
              setCourseFilter('');
              setRatingFilter(0);
            }}
          >
            <Text className="filter-text">全部评价</Text>
          </View>
          <View 
            className={`filter-item ${activeFilter === 'course' && courseFilter === 'C1手动挡' ? 'active' : ''}`}
            onClick={() => {
              setActiveFilter('course');
              setCourseFilter('C1手动挡');
            }}
          >
            <Text className="filter-text">C1手动挡</Text>
          </View>
          <View 
            className={`filter-item ${activeFilter === 'course' && courseFilter === 'C2自动挡' ? 'active' : ''}`}
            onClick={() => {
              setActiveFilter('course');
              setCourseFilter('C2自动挡');
            }}
          >
            <Text className="filter-text">C2自动挡</Text>
          </View>
          {[5, 4, 3].map(star => (
            <View 
              key={star}
              className={`filter-item ${activeFilter === 'rating' && ratingFilter === star ? 'active' : ''}`}
              onClick={() => {
                setActiveFilter('rating');
                setRatingFilter(star);
              }}
            >
              <Text className="filter-text">{star}星以上</Text>
            </View>
          ))}
        </ScrollView>
      </View>

      {/* 评价列表 */}
      {isLoading ? (
        <View className="loading-container">
          <Text>加载中...</Text>
        </View>
      ) : (
        <ScrollView 
        className="evaluation-scroll"
        refreshing={refreshing}
        onRefresh={onRefresh}
        scrollEventThrottle={16}
      >
          {filteredEvaluations.length > 0 ? (
            filteredEvaluations.map(evaluation => (
              <View key={evaluation.id} className="evaluation-item">
                <View className="evaluation-header">
                  <Image 
                    className="student-avatar" 
                    src={evaluation.studentAvatar} 
                    mode="aspectFill"
                  />
                  <View className="student-info">
                    <View className="student-name-rating">
                      <Text className="student-name">{evaluation.studentName}</Text>
                      <View className="rating-stars">
                        {renderStars(evaluation.rating)}
                      </View>
                    </View>
                    <View className="course-time">
                      <Text className="course-type">{evaluation.courseType}</Text>
                      <Text className="create-time">{evaluation.createTime}</Text>
                    </View>
                  </View>
                </View>
                <Text className="evaluation-content">{evaluation.content}</Text>
                {evaluation.images.length > 0 && (
                  <ScrollView scrollX showsHorizontalScrollIndicator={false} className="evaluation-images">
                    {evaluation.images.map((image, index) => (
                      <Image 
                        key={index}
                        className="evaluation-image"
                        src={image}
                        mode="aspectFill"
                        onClick={() => handleImagePress(evaluation.images, index)}
                      />
                    ))}
                  </ScrollView>
                )}
                {/* 操作按钮 */}
                <View className="evaluation-actions">
                  <View 
                    className={`action-btn like-btn ${evaluation.liked ? 'active' : ''}`}
                    onClick={() => handleLike(evaluation.id)}
                  >
                    <MaterialIcons 
                      name={evaluation.liked ? 'thumb-up' : 'thumb-up-off-alt'} 
                      size={16} 
                      color={evaluation.liked ? '#1890ff' : '#999'} 
                    />
                    <Text className={evaluation.liked ? 'active' : ''}>
                      点赞 ({evaluation.likeCount})
                    </Text>
                  </View>
                  <View 
                    className={`action-btn disagree-btn ${evaluation.agreed ? 'active' : ''}`}
                    onClick={() => handleDisagree(evaluation.id)}
                  >
                    <MaterialIcons 
                      name={evaluation.agreed ? 'thumb-down' : 'thumb-down-off-alt'} 
                      size={16} 
                      color={evaluation.agreed ? '#f5222d' : '#999'} 
                    />
                    <Text className={evaluation.agreed ? 'active' : ''}>
                      不赞同 ({evaluation.agreedCount})
                    </Text>
                  </View>
                </View>
              </View>
            ))
          ) : (
            <View className="empty-container">
              <MaterialIcons name="rate-review" size={80} color="#ccc" />
              <Text className="empty-text">暂无评价数据</Text>
            </View>
          )}
        </ScrollView>
      )}

      {/* 图片预览组件 */}
      {showImagePreview && (
        <View className="image-preview-overlay" onClick={closeImagePreview}>
          <View className="close-preview-btn" onClick={closeImagePreview}>
            <MaterialIcons name="close" size={24} color="#fff" />
          </View>
          <Taro.ImageViewer
            urls={previewImages}
            current={currentImageIndex}
            show={showImagePreview}
            onClose={closeImagePreview}
          />
        </View>
      )}


    </View>
  );
};

export default CoachEvaluationPage;